<?php

    use app\admin\model\AdminLog;
    use app\admin\model\Setting;
    use app\admin\model\Upload;
    use service\JsonService;
    use service\TimeService;
    use service\TreeService;
    use think\Exception;
    use think\Image;
    use think\Db;
    use think\Request;

    /**
     * Created by PhpStorm.
     * User: jackhhy
     * Date: 2019/6/26-14:14
     * Link: https://gitee.com/luckygyl/lucky_admin
     * FileName: common.php
     * Keys: ctrl+alt+L/ctrl+s(代码格式化) ctrl+J(代码提示) ctrl+R(替换)ALT+INSERT(生成代码(如GET,SET方法,构造函数等) , 光标在类中才生效)
     * CTRL+ALT+O (优化导入的类和包 需要配置) SHIFT+F2(高亮错误或警告快速定位错误)
     * CTRL+SHIFT+Z(代码向前) CTRL+SHIFT+/ (块状注释) ctrl+shift+enter(智能完善代码 如if())
     */


    /**
     * @param $arrs
     * @return bool|int
     * @author: Jackhhy <jackhhy520@qq.com>
     * @name: AddLogs
     * @describe: 日志
     */
     function AddLogs($arrs){
        $set=new Setting();
        $res=$set->getSetting();
        if((int)$res['safe']['admin_log']==2){ //关闭后台日志
            return true;
        }
         $log=new AdminLog();
         return $log->allowField(true)->save($arrs);
}


    /**
     * 缩略图生成
     * @param sting $src
     * @param intval $width
     * @param intval $height
     * @param boolean $replace
     * @param intval $type
    1、标识缩略图等比例缩放类型
    2、标识缩略图缩放后填充类型
    3、标识缩略图居中裁剪类型
    4、标识缩略图左上角裁剪类型
    5、标识缩略图右下角裁剪类型
    6、标识缩略图固定尺寸缩放类型
     * @return string
     */
    function thumb($src = '', $width = 500, $height = 500, $type = 1, $replace = false) {
        $src = './'.$src;
        if(is_file($src) && file_exists($src)) {
            $ext = pathinfo($src, PATHINFO_EXTENSION);
            $name = basename($src, '.'.$ext);
            $dir = dirname($src);
            if(in_array($ext, array('gif','jpg','jpeg','bmp','png'))) {
                $name = $name.'_thumb_'.$width.'_'.$height.'.'.$ext;
                $file = $dir.'/'.$name;
                if(!file_exists($file) || $replace == TRUE) {
                    $image = Image::open($src);
                    $image->thumb($width, $height, $type);
                    $image->save($file);
                }
                $file=str_replace("\\","/",$file);
                $file = '/'.trim($file,'./');
                return $file;
            }
        }
        $src=str_replace("\\","/",$src);
        $src = '/'.trim($src,'./');
        return $src;
    }


    /**
     * @param $address
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws phpmailerException
     * @author: Jackhhy <jackhhy520@qq.com>
     * @name: SendMail
     * @describe:发送邮件
     */
    function SendMail($address)
    {
        vendor('phpmailer.PHPMailerAutoload');
        $mail = new \PHPMailer();
        // 设置PHPMailer使用SMTP服务器发送Email
        $mail->IsSMTP();
        // 设置邮件的字符编码，若不指定，则为'UTF-8'
        $mail->CharSet='UTF-8';
        // 添加收件人地址，可以多次使用来添加多个收件人
        $mail->AddAddress($address);
        $data=db("setting")->where("key","email")->find();
        $data=json_decode($data["value"]);
        $title = $data->title;
        $message = $data->content;
        $from = $data->from_email;
        $fromname = $data->from_name;
        $smtp = $data->smtp;
        $username = $data->username;
        $password = $data->password;
        // 设置邮件正文
        $mail->Body=$message;
        // 设置邮件头的From字段。
        $mail->From=$from;
        // 设置发件人名字
        $mail->FromName=$fromname;
        // 设置邮件标题
        $mail->Subject=$title;
        // 设置SMTP服务器。
        $mail->Host=$smtp;
        // 设置使用ssl加密方式登录鉴权
        $mail->SMTPSecure = 'ssl';
        // 设置ssl连接smtp服务器的远程服务器端口号
        $mail->Port = 465;
        // 设置为"需要验证" ThinkPHP 的config方法读取配置文件
        $mail->SMTPAuth=true;
        //设置html发送格式
        $mail->isHTML(true);
        // 设置用户名和密码。
        $mail->Username=$username;
        $mail->Password=$password;
        // 发送邮件。
        return($mail->Send());
    }


    /**
     * @param $page
     * @param $limit
     * @param array $where
     * @param $tablename
     * @param string $order
     * @author: Jackhhy <jackhhy520@qq.com>
     * @name: GetPageData
     * @describe:生成分页数据
     */
    function GetPageData($page,$limit,$where,$tablename,$order="create_time desc",$tree=1,$title="title"){
        $page=empty($page)?1:$page;
        $limit=empty($limit)?10:$limit;
        if(empty($tablename)){
            return JsonService::fail("请填写表格表格");
        }
        try{
            $count=db("$tablename")->where($where)->count("id");
            $data=db("$tablename")->where($where)->order($order)->page($page)->limit($limit)->select();
           // dump($where);
            if($tree!=1){
                $data=TreeService::toFormatTree($data,$title); //格式化数据
            }
        }catch (Exception $exception){
            return JsonService::fail($exception->getMessage());
        }
        return JsonService::result(0,"",$data,$count);
}





    /**
     * @param $filename
     * @return string
     * @author: Jackhhy <jackhhy520@qq.com>
     * @name: fileext
     * @describe:获取文件后缀名
     */
    function fileext($filename) {
        return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
    }

    /**
     * @param $filepath
     * @param string $filename
     * @author: Jackhhy <jackhhy520@qq.com>
     * @name: file_down
     * @describe: 文件下载
     */
    function file_down($filepath, $filename = '') {
        if(!$filename) $filename = basename($filepath);
        if(is_ie()) $filename = rawurlencode($filename);
        $filetype = fileext($filename);
        $filesize = sprintf("%u", filesize($filepath));
        if(ob_get_length() !== false) @ob_end_clean();
        header('Pragma: public');
        header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding: binary');
        header('Content-Encoding: none');
        header('Content-type: '.$filetype);
        header('Content-Disposition: attachment; filename="'.$filename.'"');
        header('Content-length: '.$filesize);
        readfile($filepath);
        exit;
    }


    /**
     * @param $content
     * @return mixed|string
     * @author: Jackhhy <jackhhy520@qq.com>
     * @name: match_img
     * @describe: 获取内容中的图片
     */
    function match_img($content){
        preg_match('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/', $content, $match);
        return !empty($match) ? $match[1] : '';
    }


    /**
     * @param $content
     * @param string $targeturl
     * @return bool|mixed
     * @author: Jackhhy <jackhhy520@qq.com>
     * @name: grab_image
     * @describe:获取远程图片并把它保存到本地, 确定您有把文件写入本地服务器的权限
     */
    function grab_image($content, $targeturl = ''){
        preg_match_all('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/', $content, $img_array);
        $img_array = isset($img_array[1]) ? array_unique($img_array[1]) : array();

        if($img_array) {
            $path =  UPLOAD_PATH.'/'.'grap_image/'.date('Ym/d');
            $urlpath = SITE_URL.$path;
            $imgpath =  YZMPHP_PATH.$path;
            if(!is_dir($imgpath)) @mkdir($imgpath, 0777, true);
        }

        foreach($img_array as $key=>$value){
            $val = $value;
            if(strpos($value, 'http') === false){
                if(!$targeturl) return $content;
                $value = $targeturl.$value;
            }
            $ext = strrchr($value, '.');
            if($ext!='.png' && $ext!='.jpg' && $ext!='.gif' && $ext!='.jpeg') return false;
            $imgname = date("YmdHis").rand(1,9999).$ext;
            $filename = $imgpath.'/'.$imgname;
            $urlname = $urlpath.'/'.$imgname;

            ob_start();
            readfile($value);
            $data = ob_get_contents();
            ob_end_clean();
            file_put_contents($filename, $data);

            if(is_file($filename)){
                $content = str_replace($val, $urlname, $content);
            }else{
                return $content;
            }
        }
        return $content;
    }


    /**
     * 格式化字节大小
     * @param  number $size      字节数
     * @param  StringService $delimiter 数字和单位分隔符
     * @return StringService            格式化后的带单位的大小
     */
     function format_bytes($size, $delimiter = '') {
         $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
         for($i = 0; $size >= 1024 && $i < 5; $i++)
             $size /= 1024;
         return round($size, 2).$delimiter.$units[$i];
     }


    /**
     * @param $sTime
     * @return false|\service\StringService
     * @author: Jackhhy <jackhhy520@qq.com>
     * @name: friend_time
     * @describe:时间友好
     */
     function friend_time($sTime){
         return TimeService::friendlyDate($sTime);
     }
